import React, { useState } from "react";
import { Delete } from "@ct0/icons";
import { isUrl } from "@ct0/functions";

import Input from "../../components/Input";
import Button from "../../../Button";
import Field from "../../components/Field";

import type { FieldBaseType } from "../../type";
import { useStyles } from "./styles";

export default function UrlArrayField({
  field,
  showError,
  onChange,
}: {
  field: FieldBaseType<Array<string>>;
  showError: boolean;
  onChange: (v: Array<string>) => void;
}) {
  const { value, defaultValue, placeholder, suffix, disabled } = field;

  const [urls, setUrls] = useState(value ?? defaultValue ?? []);

  const classes = useStyles();

  const handler = (v: string, index: number) => {
    urls[index] = v;
    setUrls([...urls]);
    onChange(urls);
  };

  const addItem = () => {
    const newUrls = [...urls, ""];
    setUrls(newUrls);
    onChange(newUrls);
  };

  const removeItem = (index: number) => {
    const newUrls = [...urls.slice(0, index), ...urls.slice(index + 1)];
    setUrls(newUrls);
    onChange(newUrls);
  };

  return (
    <div className={classes.list}>
      {urls.map((url, index) => {
        const isValid = showError ? isUrl(url) : true;

        return (
          <div key={index} className={classes.wrap}>
            <div className={classes.content}>
              <Field labelWidth={0}>
                <Input
                  placeholder={placeholder}
                  disabled={disabled}
                  invalid={!isValid}
                  value={url}
                  type="text"
                  suffix={suffix}
                  onChange={(v) => handler(v, index)}
                />
              </Field>
              <a className={classes.remove} onClick={() => removeItem(index)}>
                <Delete />
              </a>
            </div>
          </div>
        );
      })}
      {!disabled && <Button onClick={addItem}>新增一条数据</Button>}
    </div>
  );
}
